<!--3	交通违法记录-->
<template>
    <Layout>
        <Form ref="form1" :model="dataToQuery" :label-width="120">
            <Row class="query-form" >
                <Col span="8">
                    <FormItem label="二级集团：">
                        <two-level-org org-code class="query-form-el" v-model="dataToQuery.twoLevelOrgCode" />
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="单位名称：" prop="order">
                      <!--                        <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName' :orgTree="true" :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>-->
                      <Input class="query-form-el" type="text" v-model="dataToQuery.companyName"></Input>
                    </FormItem>
                </Col>
                <Col span="8" v-if="!switchFlag">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button @click="reset1" class="ivu-btn-reset"  >重置</Button>
                    <Button type="primary" class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
                </Col>
                <Col span="8" v-else>
                    <FormItem label="季度：" prop="quarter">
                        <Select v-model="dataToQuery.quarter" placeholder="请选择季度">
                            <Option v-for="(option, index) in quarterList" :value="option.value" :key="index">{{option.label}}</Option>
                        </Select>
                    </FormItem>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="8">
                    <FormItem label="年度：" prop="year" >
                        <DatePicker class="query-form-el" type="year" placeholder="请选择年度" v-model="dataToQuery.year1" :clearable="false"
                                    @on-change="()=>{if(dataToQuery.year1 instanceof Date){dataToQuery.year = dataToQuery.year1.getFullYear().toString()}}"></DatePicker>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="车牌号：" prop="plateNumber">
                        <Input class="query-form-el" type="text" v-model="dataToQuery.plateNumber"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset1" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large"  class="ivu-btn-add" icon="md-add"  @click="addInfo">新增</Button>
                    <Button size="large" class="ivu-btn-add" icon="md-download" @click="downloadDescriptionExcel">
                      导入模板下载
                    </Button>
                    <Button size="large" class="ivu-btn-add" icon="md-cloud-upload" @click="beachUpload">批量导入</Button>
                    <download-button :api="exportUrl" :query-form="dataToQuery"/>
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" @on-selection-change = 'getSelectRows' :loading='pageStatus.loading'
            @on-sort-change="sortChange"
            border :columns="columns1"  :data="dataTable" >
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24" >
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>
        <Modal :title="this.getModalTitle('交通违法记录')" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow"  :width=800 :styles="{maxHeight:'700px'}"  class-name='limit-height-dialog'>
            <Row>
                <Col span="24">
                    <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false" :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?100:null" :label-position="mode === 'view'?'right':'top'">

                        <Row v-if="mode === 'view'" type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='单位名称：' prop='companyId'>
                                    <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                                    <!--<Input v-else class='query-form-el' placeholder="请填写单位名称" type='text' v-model='dataToView.companyId'></Input>-->
                                    <div v-else>
                                        <cascader-dom  v-if="show"  class='query-form-el' ref='orgCascader' @setOrgInfo='setCompanyId' @setOrgname="setCompanyName" :orgTree="true"
                                                       :currentOrgId="dataToView.companyId" :rootOrgId="dataToView.belongOrgId"
                                                       :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}" ></cascader-dom>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='号牌号码：' prop='carId'>
                                    <div v-if="mode === 'view'">{{ dataToView.plateNumber }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写号牌号码" type='text' readonly @on-focus="carModel=true" v-model='dataToView.plateNumber'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='号牌种类：' prop='carId'>
                                    <div v-if="mode === 'view'">{{ dataToView.carType }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写号牌号码" type='text' readonly v-model='dataToView.carType'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='当事人：' prop='driverId'>
                                    <div v-if="mode === 'view'">{{ dataToView.driverId }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写当事人" type='text' v-model='dataToView.driverId'></Input>
                                    <!--readonly @on-focus="driverModel=true"-->
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='违法时间：' prop='violationDate'>
                                    <div v-if="mode === 'view'">{{renderViewDateTime( dataToView.violationDate) }}</div>
                                    <DatePicker v-else class="query-form-el" placeholder="请选择违法时间" type="datetime" v-model='dataToView.violationDate' ></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='违法扣分：' prop='score'>
                                    <div v-if="mode === 'view'">{{ dataToView.score }}</div>
                                    <!--<InputNumber :min="0" :max="12" v-else class='query-form-el' placeholder="请填写违法扣分" type='text' v-model='dataToView.score'></InputNumber>-->
                                    <Select v-else v-model="dataToView.score" placeholder="请选择违法扣分" filterable>
                                        <Option v-for="item in violationScore" :key="item" :label="item" :value="item"></Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='违法地址：' prop='accAddress'>
                                    <div v-if="mode === 'view'">{{ dataToView.accAddress }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写违法地址" type='text' v-model='dataToView.accAddress'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="23">
                                <FormItem label='违法内容：' prop='violationItem'>
                                    <div v-if="mode === 'view'">{{ dataToView.violationItem }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写违法内容" type='text' v-model='dataToView.violationItem'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='填报人：' prop='createUserName'>
                                    <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写填报人" readonly type='text' v-model='dataToView.createUserName'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='填报时间：' prop='createDate'>
                                    <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                                    <DatePicker v-else class="query-form-el" placeholder="请选择填报时间" readonly v-model='dataToView.createDate' ></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <!--<Row type="flex" justify="space-around" class="code-row-bg">-->
                        <!--<Col span="11">-->
                        <!--<FormItem label='填报人手机号：' prop='registrantPhone'>-->
                        <!--<div v-if="mode === 'view'">{{ dataToView.registrantPhone }}</div>-->
                        <!--<Input v-else class='query-form-el' placeholder="请填写填报人手机号" type='text' v-model='dataToView.registrantPhone'></Input>-->
                        <!--</FormItem>-->
                        <!--</Col>-->
                        <!--<Col span="11"></Col>-->
                        <!--</Row>-->

                    </Form>
                </Col>
                <Modal :mask-closable="false" :transfer=false footer-hide v-model="carModel" :width=900 title="车辆选择" @on-cancel="carModel=false">
                    <car-info v-if="carModel" v-show="carModel" :modelSelect="carModel"
                              :companyId="dataToView.companyId"  @getSelectModelData='getSelectCar'></car-info>
                </Modal>

                <Modal :mask-closable="false" :transfer=false footer-hide v-model="driverModel" :width=900 title="驾驶员选择" @on-cancel="driverModel=false">
                    <car-driver v-if="driverModel" v-show="driverModel" :modelSelect="driverModel"
                                @getSelectModelData='getSelectDriver'></car-driver>
                </Modal>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-save' @click="submit('dialogForm')" >确定</Button>
                <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>

        <Modal :mask-closable="false" :transfer=false  v-model="model3" :width=700 title="交通违法记录导入" @on-cancel="cancelMap">
            <Form  ref="map" :show-message="false" :model="map" label-position="top">
                <Row type="flex" justify="space-around" class="code-row-bg">
                    <Col span="23">
                        <FormItem  label="" prop="file">
                            <div>
                                <Upload ref="upload1"
                                        :before-upload="handleUpload "
                                        :format="['xlsx', 'xls']"
                                        accept=".xlsx, .xls"
                                        :max-size="10240"
                                        type="drag"
                                        :action="uploadUrl">
                                    <div style="padding: 10px">
                                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                        <p>点击将文件拖拽到这里上传</p>
                                        <span style="font-size:8px;color: #797a64">仅支持上传单个excel </span>
                                    </div>
                                </Upload>
                            </div>
                            <div v-if="fileTrue">
                                <a>{{ map.file.name }}</a>
                                <Button type="text" icon="md-trash" @click="map.file = {},fileTrue = false" style="margin-left: 5px;margin-bottom: 3px"/>
                            </div>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' :disabled="uploadDissabled" @click="submitFile('map')">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="cancelMap">取消</Button>
            </div>
        </Modal>

        <Modal title="导入详情" v-model="logInfoModel" :transfer=false :mask-closable="false">
            <Row type="flex" justify="space-around" class="code-row-bg">
                <Col span="23">
                    <div v-html="logInfo"></div>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-cancel' @click="logInfoModel=false,logInfo=null">关闭</Button>
            </div>
        </Modal>
    </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import pageCommonFunction from '@/components/pageCommonFunction.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import carInfo from './saCarInfo'
import carDriver from './saCarDriver'
import constant from '../../../../common/user.js';

var cascaderDom = () => import('@/components/cascader-dom.vue');
export default {
  components: {cascaderDom, carInfo, carDriver},
  data() {
    return {
      ...this.createCommonDataField(),
      imgUrl: "",
      columns1: [
        {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {key: 'companyName', title: '单位名称', align: 'center', minWidth: 200,},
        {key: 'plateNumber', title: '号牌号码', align: 'center', minWidth: 120,},
        {key: 'carType', title: '号牌种类', align: 'center', minWidth: 120,},
                    { key:'driverId',title: '当事人',  align: 'center', minWidth: 120,  },
                    { key:'violationDate',title: '违法时间', sortable: "custom", align: 'center', minWidth: 120,  render: this.renderCellDateTime },
                    { key:'accAddress',title: '违法地址',  align: 'center', minWidth: 120,  },
                    { key:'violationItem',title: '违法内容',  align: 'center', minWidth: 120, tooltip: true },
                    { key:'score',title: '违法扣分',  align: 'center', minWidth: 120,  },
                    { key:'year',title: '年份',  align: 'center', minWidth: 120,  },
                    { key:'quarter',title: '季度',  align: 'center', minWidth: 120,render: (h, params) => {
                            return h('span', params.row.quarter+"季度");}},
                    { key:'createDate',title: '填报时间', sortable: "custom", align: 'center',minWidth: 120, render: this.renderCellDate},
                    this.getActionColumns(),
                ],
                ruleCustom : {
                    companyId: [ { required: true, message: '请填写单位名称', trigger: 'change',}],
                    carId: [ { required: true, message: '请填写号牌号码', trigger: 'change',}],
                    // driverId: [ { required: true, message: '请填写当事人', trigger: 'change',}],
                    violationItem: [ { required: true, message: '请填写违法内容', trigger: 'change',}],
                    violationDate: [ { required: true, message: '请填写违法时间', trigger: 'change',type:'date'}],
                    score: [ { required: true, message: '请填写违法扣分', trigger: 'change',type: 'number' }],
                    accAddress: [ { required: true, message: '请填写违法地址', trigger: 'change',}],
                    createUserName: [ { required: true, message: '请填写填报人', trigger: 'change',}],
                    createDate: [ { required: true, message: '请填写填报时间', trigger: 'change',type:'date'}],
                    // cellPhone: [ {
                    //     validator: (rule, value, callback) => {
                    //         if(!(/^1[3456789]\d{9}$/.test(this.dataToView.cellPhone))){
                    //             callback(' ');
                    //             // this.$Message.error("请填写有效的的手机号")
                    //         } else {
                    //             callback()
                    //         }
                    //     },
                    //     required: true,
                    //     trigger: 'blur'
                    // }],
                },
                tableHeight:10,
                dictMap: {},
                punishment: false,
                penaltyAmount:true,
                // api
                queryUrl:Api.querySaTraff.replace('{{table}}','violation'),
                exportUrl:Api.exportSaTraff.replace('{{table}}','violation'),
                deleteUrl:Api.deleteSaTraff.replace('{{table}}','violation'),
                getUrl:Api.getSaTraff.replace('{{table}}','violation'),
                updateUrl:Api.updateSaTraff.replace('{{table}}','violation'),
                saveUrl:Api.saveSaTraff.replace('{{table}}','violation'),
                uploadUrl:Api.uploadSaTraff.replace('{{table}}','violation'),

                currentUser: JSON.parse(sessionStorage('userId').get('userId')),

                twoLevel:[],
                show:true,
                driverModel:false,
                carModel:false,
                violationScore: constant.violationScore,
                quarterList:[
                    {value: '一', label: '一季度'},
                    {value: '二', label: '二季度'},
                    {value: '三', label: '三季度'},
                    {value: '四', label: '四季度'}
                    ],

                fileTrue: false,
                map:{},
                model3:false,
                uploadDissabled: false,
                logInfoModel:false,
                logInfo:null
            }
        },
        async mounted() {
            this.setTableHeight();
            // this.selectSecGroupNames()
            this.dataToQuery.year1 = new Date()
            this.dataToQuery.year = new Date().getFullYear().toString()
            this.query();
        },
        methods:{
            ...pageCommonFunction,
            submitFile(map){
                this.$refs[map].validate((valid) => {
                    if (valid) {
                        this.uploadDissabled = true
                        let formData = new FormData();
                        formData.append("file", this.map.file);
                        formData.append("createUserId", this.currentUser.userId);
                        formData.append("createOrgId", this.currentUser.orgInfo.orgId);
                        this.$http.post(this.uploadUrl, formData).then((res) => {
                            this.uploadDissabled = false
                            if (res.data.status == "200") {
                                // this.$Message.success("交通违法记录导入成功! 导入详情请查看控制台");
                                this.logInfoModel = true
                                this.logInfo = res.data.data
                                this.query()
                            } else {
                                this.$Message.error(res.data.msg);
                            }
                            this.map={}
                            this.fileTrue = false
                            this.model3=false
                        }).catch(e => {
                            console.log(e);
                            this.model3=false
                            this.map={}
                            this.uploadDissabled = false
                            this.$Message.error("导入失败！请检查导入文档的格式是否正确");
                        })
                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })

            },
            handleUpload (file) {
                this.map.file = file;
                this.fileTrue = true
                return false;
            },
            cancelMap() {
                this.model3 = false
                this.fileTrue = false
                this.map ={}
            },
            beachUpload(){
                this.model3 = true
                this.fileTrue = false
                this.map ={}
            },
            downloadDescriptionExcel() {
              let link = document.createElement('a');
              link.style.display = 'none';
              link.href = Api.templateDownload + '5';
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link)
            },

            getSelectCar(row) {
                this.$set(this.dataToView,'carId', row.id)
                this.dataToView.plateNumber = row.plateNumber;
                this.dataToView.carType = row.carType;
                this.dataToView.companyId = row.companyId;
                this.dataToView.companyName = row.companyName;
                this.carModel = false;
            },
            getSelectDriver(row) {
                this.$set(this.dataToView,'driverId', row.id)
                // this.dataToView.driverId = row.id;
                this.dataToView.userName = row.userName;
                this.driverModel = false;
            },
            selectSecGroupNames(){
                this.$http.get(Api.quqeryTwoOrgInfo).then(res => {
                    this.twoLevel=res.data.data
                }).catch(e => {
                })
            },
            deleteData(params) {
                this.deleteDateAjax(params);
            },
            query() {
                this.queryAjax();
            },
            reset1() {
                this.dataToQuery = {
                    year1: new Date(),
                    year : new Date().getFullYear().toString()
                };
                if (this.$refs.queryOrgCascader) {
                    this.$refs.queryOrgCascader.resetCurrentOrg();
                }
                this.pagedata.currentPage=1
                this.query()
            },
            submit(name) {
                this.submitAjax(name);
            },
            createEmptyDataToAdd(){
                return {
                    createDate: new Date(),
                    createUserId: this.currentUser.userId,
                    createUserName:this.currentUser.userName,
                    id:this.get_uuid(),
                    score: null,
                    // idFiles:[],

                }
            },
            // async afterDataToViewInit() {
            //     await this.getFiles('id');
            // },
        },
        watch:{
        },
    }
</script>

<style lang='css' scoped>
    .ivu-form-item {
        padding-right: 20px;
    }

    .query-form-el, .ivu-date-picker, .ivu-input-wrapper {
        width: 100%;
    }

</style>
